// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//


#include <melon/futures/future.h>
#include <melon/futures/promise.h>
#include <string>
#include <pollux/common/file/file_systems.h>

namespace kumo::pollux::process {

class Profiler {
 public:
  /// Starts periodic production of perf reports.
  static void start(
      const std::string& path,
      std::function<void()> extraStart = nullptr,
      std::function<std::string()> extraReport = nullptr);

  // Stops profiling background associated threads. Threads are stopped on
  // return.
  static void stop();

  static bool isRunning();

 private:
  static void copyToResult(const std::string* result = nullptr);
  static void makeProfileDir(std::string path);
  static std::thread startSample();
  // Returns after 'seconds' of wall time or sooner if interrupted by stop().
  static bool interruptibleSleep(int32_t seconds);
  static void stopSample(std::thread thread);
  static void threadFunction();

  static tsan_atomic<bool> profileStarted_;
  static std::thread profileThread_;
  static std::mutex profileMutex_;
  static std::shared_ptr<pollux::filesystems::FileSystem> fileSystem_;
  static tsan_atomic<bool> isSleeping_;
  static tsan_atomic<bool> shouldStop_;
  static melon::Promise<bool> sleepPromise_;

  // Directory where results are deposited. Results have unique names within
  // this.
  static std::string resultPath_;

  // indicates if the results of the the profile should be saved at stop.
  static tsan_atomic<bool> shouldSaveResult_;

  // Time of starting the profile. Seconds from epoch.
  static tsan_atomic<int64_t> sampleStartTime_;

  // CPU time at start of profile.
  static int64_t cpuAtSampleStart_;

  // CPU time at last periodic check.
  static int64_t cpuAtLastCheck_;

  static std::function<void()> startExtra_;
  static std::function<std::string()> extraReport_;
};

} // namespace kumo::pollux::process
